Number of distinct islands II [Hash]¶
Time: O((MxN)xLog(MxN)); Space: O(MxN); hard
Given a non-empty 2D array grid of 0’s and 1’s, an island is a group of 1’s (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.
Count the number of distinct islands. An island is considered to be the same as another if they have the same shape, or have the same shape after rotation (90, 180, or 270 degrees only) or reflection (left/right direction or up/down direction).
The length of each dimension in the given grid does not exceed 50.
Example 1:
Input: grid =
[
[1,1,0,0,0],
[1,0,0,0,0],
[0,0,0,0,1],
[0,0,0,1,1]
]
Output: 1
Explanation:
Notice that:
11 1 and 1 11
are considered same island shapes.
Because if we make a 180 degrees clockwise rotation on the first island, then two islands will have the same shapes.
Example 2:
Input: grid =
[
[1,1,1,0,0],
[1,0,0,0,1],
[0,1,0,0,1],
[0,1,1,1,0]
]
Output: 2
Explanation:
Here are the two distinct islands:
111 1 and 1 1
Notice that:
111 1 and 1 111
are considered same island shapes.
Because if we flip the first array in the up/down direction, then they have the same shapes.
[5]:
class Solution1(object):
"""
Time: O((M*N)*Log(M*N))
Space: O(M*N)
"""
def numDistinctIslands2(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
directions = [(0, -1),
(0, 1),
(-1, 0),
(1, 0)]
def dfs(i, j, grid, island):
if not (0 <= i < len(grid) and \
0 <= j < len(grid[0]) and \
grid[i][j] > 0):
return False
grid[i][j] *= -1
island.append((i, j))
for d in directions:
dfs(i + d[0], j + d[1], grid, island)
return True
def normalize(island):
shapes = [[] for _ in range(8)]
for x, y in island:
rotations_and_reflections = [[ x, y], [ x, -y],
[-x, y], [-x, -y],
[ y, x], [ y, -x],
[-y, x], [-y, -x]]
for i in range(len(rotations_and_reflections)):
shapes[i].append(rotations_and_reflections[i])
for shape in shapes:
shape.sort() # Time: O(IlogI), I is the size of the island, the max would be (MxN)
origin = list(shape[0])
for p in shape:
p[0] -= origin[0]
p[1] -= origin[1]
return min(shapes)
islands = set()
for i in range(len(grid)):
for j in range(len(grid[0])):
island = []
if dfs(i, j, grid, island):
islands.add(str(normalize(island)))
return len(islands)
[7]:
s = Solution1()
grid = [
[1,1,0,0,0],
[1,0,0,0,0],
[0,0,0,0,1],
[0,0,0,1,1]
]
assert s.numDistinctIslands2(grid) == 1
grid = [
[1,1,1,0,0],
[1,0,0,0,1],
[0,1,0,0,1],
[0,1,1,1,0]
]
assert s.numDistinctIslands2(grid) == 2
See also:¶
https://leetcode.com/problems/number-of-distinct-islands-ii
https://www.lintcode.com/problem/number-of-distinct-islands-ii/description